<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Markdown 编辑器 - 自动保存模式</title>
    <link rel="stylesheet" href="/static/css/index.css" />
    <style>
        :root {
            --primary-color: #4CAF50;
            --primary-hover: #45a049;
            --border-color: #ddd;
            --bg-color: #f5f5f5;
            --text-secondary: #666;
            --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            --sidebar-width: 280px;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: var(--bg-color);
            color: #333;
            line-height: 1.6;
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow: hidden;
        }

        header {
            background-color: white;
            padding: 15px 20px;
            box-shadow: var(--shadow);
            display: flex;
            justify-content: space-between;
            align-items: center;
            z-index: 10;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .logo {
            font-size: 22px;
            font-weight: bold;
            color: var(--primary-color);
        }

        .toolbar {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s, transform 0.1s;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .btn:hover {
            background-color: var(--primary-hover);
        }

        .btn:active {
            transform: translateY(1px);
        }

        .btn-secondary {
            background-color: #6c757d;
        }

        .btn-secondary:hover {
            background-color: #5a6268;
        }

        .main-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            width: var(--sidebar-width);
            background-color: white;
            border-right: 1px solid var(--border-color);
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
        }

        .sidebar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
        }

        .file-list {
            flex: 1;
            overflow-y: auto;
        }

        .file-item {
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 5px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .file-item:hover {
            background-color: #f0f0f0;
        }

        .file-item.active {
            background-color: #e3f2fd;
            font-weight: bold;
        }

        .file-actions {
            display: flex;
            gap: 5px;
        }

        .file-action-btn {
            background: none;
            border: none;
            cursor: pointer;
            color: var(--text-secondary);
            font-size: 14px;
        }

        .file-action-btn:hover {
            color: var(--primary-color);
        }

        .editor-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        #vditor {
            flex: 1;
            border: none;
            border-radius: 0;
        }

        .status-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 16px;
            background-color: white;
            border-top: 1px solid var(--border-color);
            font-size: 14px;
        }

        #status {
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .save-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: #4CAF50;
        }

        .save-indicator.pending {
            background-color: #ff9800;
        }

        .save-indicator.error {
            background-color: #f44336;
        }

        .auto-save {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .document-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .document-id {
            background-color: #e9ecef;
            padding: 4px 8px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 14px;
        }

        @media (max-width: 768px) {
            .sidebar {
                position: absolute;
                left: -100%;
                z-index: 100;
                height: 100%;
                transition: left 0.3s;
            }

            .sidebar.open {
                left: 0;
            }
        }

        .search-box {
            margin-bottom: 15px;
            position: relative;
        }

        .search-box input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
        }

        .empty-state {
            text-align: center;
            padding: 30px 0;
            color: var(--text-secondary);
        }

        /* 重命名模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            width: 400px;
            max-width: 90%;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
        }

        .modal-body input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            margin-bottom: 15px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .document-name {
            font-weight: bold;
            color: #333;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
        }

        .document-name:hover {
            text-decoration: underline;
        }

        .save-btn {
            background-color: #2196F3;
        }

        .save-btn:hover {
            background-color: #0b7dda;
        }
    </style>
</head>
<body>
    <header>
        <div class="header-left">
            <div class="logo">MD Editor</div>
            <div class="toolbar">
                <button class="btn" onclick="newDocument()">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M12 5V19M5 12H19" stroke="white" stroke-width="2" stroke-linecap="round"/>
                    </svg>
                    新建
                </button>
<!--                <button class="btn save-btn" onclick="manualSave()">-->
<!--                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">-->
<!--                        <path d="M17 3H5C3.89 3 3 3.9 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V7L17 3ZM12 19C10.34 19 9 17.66 9 16C9 14.34 10.34 13 12 13C13.66 13 15 14.34 15 16C15 17.66 13.66 19 12 19ZM15 9H5V5H15V9Z" fill="white"/>-->
<!--                    </svg>-->
<!--                    保存-->
<!--                </button>-->
            </div>
        </div>
        <div class="document-info">
            <span>当前文档:</span>
            <span class="document-name" id="current-doc-name" onclick="renameCurrentDocument()">无标题文档</span>
            <span class="document-id" id="current-doc-id"></span>
        </div>
    </header>

    <div class="main-container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h3>本地文档</h3>
                <button class="file-action-btn" onclick="refreshFileList()" title="刷新">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M17.65 6.35C16.2 4.9 14.21 4 12 4C7.58 4 4.01 7.58 4.01 12C4.01 16.42 7.58 20 12 20C15.73 20 18.84 17.45 19.73 14H17.65C16.83 16.33 14.61 18 12 18C8.69 18 6 15.31 6 12C6 8.69 8.69 6 12 6C13.66 6 15.14 6.69 16.22 7.78L13 11H20V4L17.65 6.35Z" fill="currentColor"/>
                    </svg>
                </button>
            </div>

            <div class="search-box">
                <input type="text" placeholder="搜索文档..." oninput="filterFiles(this.value)">
            </div>

            <div class="file-list" id="file-list">
                <div class="empty-state">暂无文档</div>
            </div>
        </div>

        <div class="editor-container">
            <div id="vditor"></div>

            <div class="status-bar">
                <div id="status">
                    <div class="save-indicator" id="save-indicator"></div>
                    <span>就绪</span>
                </div>
                <div class="auto-save">
                    <span>自动保存已启用</span>
                </div>
                <span id="charCount">0 字符</span>
            </div>
        </div>
    </div>

    <!-- 重命名模态框 -->
    <div class="modal" id="rename-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>重命名文档</h3>
                <button class="modal-close" onclick="closeRenameModal()">&times;</button>
            </div>
            <div class="modal-body">
                <input type="text" id="rename-input" placeholder="请输入新文档名称">
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeRenameModal()">取消</button>
                <button class="btn" onclick="confirmRename()">确认</button>
            </div>
        </div>
    </div>

    <script src="static/js/index.min.js"></script>
    <script>
        // 全局变量
        let vditorInstance;
        let isModified = false;
        let currentDocumentId = null;
        let saveTimeout = null;
        let renamingDocumentId = null;
        let currentDocumentName = "无标题文档";
        let isSaving = false;
        let autoSaveInterval = null;

        // 初始化应用
        document.addEventListener("DOMContentLoaded", () => {
            // 从URL获取文档ID
            const urlParams = new URLSearchParams(window.location.search);
            const documentId = urlParams.get('document_id');

            initializeEditor();
            setupAutoSave();
            loadFileList();

            if (documentId && documentId !== "new") {
                // 加载指定文档
                loadDocument(documentId);
            } else {
                // 没有指定文档，显示空编辑器
                currentDocumentId = null;
                updateUI();
            }

            // 设置beforeunload提示
            window.addEventListener('beforeunload', (e) => {
                if (isModified && !isSaving) {
                    e.preventDefault();
                    e.returnValue = '您有未保存的更改，确定要离开吗？';
                    return e.returnValue;
                }
            });
        });

        // 初始化编辑器
        function initializeEditor() {
            try {
                vditorInstance = new Vditor('vditor', {
                    height: '100%',
                    toolbarConfig: {
                        pin: true
                    },
                    cache: {
                        enable: false
                    },
                    value: "",
                    preview: {
                        delay: 500,
                    },
                    input: (content) => {
                        document.getElementById('charCount').textContent = `${content.length} 字符`;

                        // 如果是新文档且没有标题，尝试使用第一行作为标题
                        if (currentDocumentName === "无标题文档" || currentDocumentName === "新文档") {
                            const firstLine = content.split('\n')[0];
                            if (firstLine && firstLine.trim().length > 0) {
                                const potentialTitle = firstLine.replace(/^#+\s*/, '').trim();
                                if (potentialTitle.length > 0) {
                                    currentDocumentName = potentialTitle;
                                    document.getElementById('current-doc-name').textContent = currentDocumentName;
                                }
                            }
                        }

                        isModified = true;
                        updateSaveIndicator('pending');

                        // 自动保存延迟处理
                        if (saveTimeout) {
                            clearTimeout(saveTimeout);
                        }

                        saveTimeout = setTimeout(() => {
                            if (isModified && !isSaving && currentDocumentId) {
                                saveDocument();
                            }
                        }, 1500);
                    },
                    after: () => {
                        console.log('Vditor 初始化完成');
                        const content = vditorInstance.getValue();
                        document.getElementById('charCount').textContent = `${content.length} 字符`;
                    }
                });
            } catch (error) {
                console.error('Vditor初始化错误:', error);
                showStatus('编辑器初始化失败: ' + error.message, 5000);
            }
        }

        // 设置自动保存
        function setupAutoSave() {
            // 定期保存（每30秒一次），即使没有修改
            if (autoSaveInterval) {
                clearInterval(autoSaveInterval);
            }
            
            autoSaveInterval = setInterval(() => {
                if (isModified && currentDocumentId && !isSaving) {
                    saveDocument();
                }
            }, 30000);
        }

        // 更新保存状态指示器
        function updateSaveIndicator(state) {
            const indicator = document.getElementById('save-indicator');
            indicator.className = 'save-indicator';

            if (state === 'pending') {
                indicator.classList.add('pending');
            } else if (state === 'error') {
                indicator.classList.add('error');
            }
        }

        // 显示状态信息
        function showStatus(message, duration = 3000) {
            const statusElement = document.getElementById('status');
            statusElement.querySelector('span').textContent = message;

            if (duration) {
                setTimeout(() => {
                    if (statusElement.querySelector('span').textContent === message) {
                        statusElement.querySelector('span').textContent = '就绪';
                        updateSaveIndicator();
                    }
                }, duration);
            }
        }

        // 更新UI状态
        function updateUI() {
            if (currentDocumentId) {
                document.getElementById('current-doc-id').textContent = currentDocumentId;
            } else {
                document.getElementById('current-doc-id').textContent = '';
            }

            // 更新文档名称显示
            document.getElementById('current-doc-name').textContent = currentDocumentName;

            // 加载文件列表
            loadFileList();
        }

        // 新建文档
        async function newDocument() {
            // 如果有未保存的更改，先保存
            if (isModified && currentDocumentId) {
                if (!confirm('当前文档有未保存的更改，是否先保存？')) {
                    // 用户选择不保存，直接创建新文档
                    resetEditor();
                    return;
                }

                const saveSuccess = await saveDocument();
                if (!saveSuccess) {
                    showStatus('保存失败，无法创建新文档', 3000);
                    return;
                }
            }

            try {
                const response = await fetch('/new-document', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });

                const result = await response.json();

                if (result.status === 'success') {
                    // 更新UI
                    currentDocumentId = result.document_id;
                    currentDocumentName = "新文档";

                    // 清空编辑器
                    vditorInstance.setValue("");
                    isModified = false;
                    updateSaveIndicator();

                    // 更新URL
                    window.history.replaceState({}, '', `/?document_id=${currentDocumentId}`);

                    // 更新UI
                    updateUI();

                    showStatus('已创建新文档', 2000);
                } else {
                    throw new Error(result.message || '创建文档失败');
                }
            } catch (error) {
                console.error('创建文档错误:', error);
                showStatus('创建失败: ' + error.message, 5000);
            }
        }

        // 重置编辑器状态
        function resetEditor() {
            // 清除自动保存定时器
            if (saveTimeout) {
                clearTimeout(saveTimeout);
                saveTimeout = null;
            }
            
            currentDocumentId = null;
            currentDocumentName = "无标题文档";
            vditorInstance.setValue("");
            isModified = false;
            updateSaveIndicator();
            window.history.replaceState({}, '', '/');
            updateUI();
            showStatus('已重置编辑器', 2000);
        }

        // 手动保存文档
        async function manualSave() {
            if (!currentDocumentId) {
                // 如果没有当前文档，先创建一个
                await newDocument();
                return;
            }

            await saveDocument();
        }

        // 保存文档
        async function saveDocument() {
            if (!vditorInstance || isSaving) {
                return false;
            }

            if (!currentDocumentId) {
                // 如果没有当前文档，先创建一个
                await newDocument();
                return true;
            }

            const content = vditorInstance.getValue();

            // 如果内容为空，不保存
            if (!content.trim()) {
                showStatus('内容为空，无需保存', 2000);
                return true;
            }

            isSaving = true;
            updateSaveIndicator('pending');

            try {
                // 发送保存请求
                const response = await fetch(`/save-document/${currentDocumentId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        content: content,
                        name: currentDocumentName
                    })
                });

                const result = await response.json();

                if (result.status === 'success') {
                    isModified = false;
                    isSaving = false;
                    updateSaveIndicator();

                    showStatus('已保存', 2000);

                    // 刷新文件列表
                    loadFileList();
                    return true;
                } else {
                    throw new Error(result.message || '保存失败');
                }

            } catch (error) {
                console.error('保存错误:', error);
                isSaving = false;
                updateSaveIndicator('error');
                showStatus('保存失败: ' + error.message, 5000);
                return false;
            }
        }

        // 加载文档
        async function loadDocument(documentId) {
            // 检查当前是否有未保存的更改
            if (isModified && currentDocumentId && currentDocumentId !== documentId) {
                if (!confirm('当前文档有未保存的更改，是否先保存？')) {
                    // 用户选择不保存，直接加载新文档
                    proceedWithLoading(documentId);
                    return;
                }

                const saveSuccess = await saveDocument();
                if (!saveSuccess) {
                    showStatus('保存失败，无法加载新文档', 3000);
                    return;
                }
            }

            proceedWithLoading(documentId);
        }

        // 实际执行文档加载
        async function proceedWithLoading(documentId) {
            // 清除之前的自动保存定时器
            if (saveTimeout) {
                clearTimeout(saveTimeout);
                saveTimeout = null;
            }
            
            try {
                showStatus('正在加载文档...', 0);
                
                // 通过API获取文档内容和元数据
                const response = await fetch(`/document/${documentId}/content`);
                const result = await response.json();
                
                if (result.status !== 'success') {
                    throw new Error(result.message || '加载文档失败');
                }

                // 获取文档内容和名称
                const content = result.content || "";
                currentDocumentName = result.metadata.name || "无标题文档";

                // 更新编辑器内容
                vditorInstance.setValue(content);

                // 更新当前文档ID
                currentDocumentId = documentId;
                isModified = false;
                updateSaveIndicator();

                // 更新UI
                updateUI();

                // 更新URL
                window.history.replaceState({}, '', `/?document_id=${documentId}`);

                showStatus('文档已加载', 2000);
            } catch (error) {
                console.error('加载文档错误:', error);
                showStatus('加载失败: ' + error.message, 3000);
            }
        }

        // 加载文件列表
        async function loadFileList() {
            try {
                const response = await fetch('/list-documents');
                const result = await response.json();

                const fileList = document.getElementById('file-list');
                fileList.innerHTML = '';

                if (result.documents && result.documents.length > 0) {
                    result.documents.forEach(doc => {
                        const fileItem = document.createElement('div');
                        fileItem.className = 'file-item';
                        if (doc.id === currentDocumentId) {
                            fileItem.classList.add('active');
                        }

                        fileItem.innerHTML = `
                            <div>
                                <div>${doc.name}</div>
                                <small>${new Date(doc.updated_at).toLocaleString()}</small>
                            </div>
                            <div class="file-actions">
                                <button class="file-action-btn" onclick="renameFile('${doc.id}', '${doc.name.replace(/'/g, "\\'")}', event)" title="重命名">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.9959.9959 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" fill="currentColor"/>
                                    </svg>
                                </button>
                                <button class="file-action-btn" onclick="deleteFile('${doc.id}', event)" title="删除">
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path d="M6 19C6 20.1 6.9 21 8 21H16C17.1 21 18 20.1 18 19V7H6V19ZM19 4H15.5L14.5 3H9.5L8.5 4H5V6H19V4Z" fill="currentColor"/>
                                    </svg>
                                </button>
                            </div>
                        `;

                        fileItem.addEventListener('click', () => {
                            openFile(doc.id);
                        });

                        fileList.appendChild(fileItem);
                    });
                } else {
                    fileList.innerHTML = '<div class="empty-state">暂无文档</div>';
                }
            } catch (error) {
                console.error('加载文件列表错误:', error);
            }
        }

        // 过滤文件列表
        function filterFiles(query) {
            const fileItems = document.querySelectorAll('.file-item');

            fileItems.forEach(item => {
                const fileName = item.querySelector('div').textContent.toLowerCase();
                if (fileName.includes(query.toLowerCase())) {
                    item.style.display = 'flex';
                } else {
                    item.style.display = 'none';
                }
            });
        }

        // 刷新文件列表
        function refreshFileList() {
            loadFileList();
            showStatus('已刷新文件列表', 2000);
        }

        // 打开文件
        function openFile(documentId) {
            if (documentId === currentDocumentId) {
                return; // 已经是当前文档，不需要加载
            }

            loadDocument(documentId);
        }

        // 删除文件
        async function deleteFile(documentId, event) {
            if (event) {
                event.stopPropagation();
            }

            if (confirm('确定要删除这个文档吗？此操作不可恢复。')) {
                try {
                    const response = await fetch(`/document/${documentId}`, {
                        method: 'DELETE'
                    });

                    const result = await response.json();

                    if (result.status === 'success') {
                        if (currentDocumentId === documentId) {
                            // 如果删除的是当前文档，清空编辑器
                            resetEditor();
                        }

                        loadFileList();
                        showStatus('文档已删除', 2000);
                    } else {
                        throw new Error(result.message || '删除失败');
                    }
                } catch (error) {
                    console.error('删除文件错误:', error);
                    showStatus('删除失败: ' + error.message, 3000);
                }
            }
        }

        // 重命名当前文档
        function renameCurrentDocument() {
            if (!currentDocumentId) {
                showStatus('请先创建或打开文档', 3000);
                return;
            }

            renameFile(currentDocumentId, currentDocumentName);
        }

        // 重命名文件
        function renameFile(documentId, currentName, event) {
            if (event) {
                event.stopPropagation();
            }

            renamingDocumentId = documentId;
            const renameInput = document.getElementById('rename-input');
            renameInput.value = currentName;

            // 显示模态框
            document.getElementById('rename-modal').style.display = 'flex';
            renameInput.focus();
            renameInput.select();
        }

        // 关闭重命名模态框
        function closeRenameModal() {
            document.getElementById('rename-modal').style.display = 'none';
            renamingDocumentId = null;
        }

        // 确认重命名
        async function confirmRename() {
            const newName = document.getElementById('rename-input').value.trim();

            if (!newName) {
                alert('文档名称不能为空');
                return;
            }

            try {
                const response = await fetch(`/document/${renamingDocumentId}/rename`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ name: newName })
                });

                const result = await response.json();

                if (result.status === 'success') {
                    closeRenameModal();

                    // 如果重命名的是当前文档，更新文档名称显示
                    if (currentDocumentId === renamingDocumentId) {
                        currentDocumentName = newName;
                        document.getElementById('current-doc-name').textContent = newName;
                    }

                    // 保存文档以更新名称
                    if (isModified) {
                        await saveDocument();
                    }

                    loadFileList();
                    showStatus('文档已重命名', 2000);
                } else {
                    throw new Error(result.message || '重命名失败');
                }
            } catch (error) {
                console.error('重命名文件错误:', error);
                showStatus('重命名失败: ' + error.message, 3000);
            }
        }
    </script>
</body>
</html>